from flask import Flask
from flask.logging import default_handler
import logging
from logging.handlers import RotatingFileHandler


class LogHandle:

    def __init__(self, app: Flask = None):
        if app is not None:
            self.init_app(app)

    def init_app(self, app: Flask):

        log_level = app.config.get("LOG_LEVEL")
        filename = app.config.get("LOG_DIR")
        max_bytes = app.config.get("MAX_BYTES")
        backup_count = app.config.get("BACKUP_COUNT")

        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)

        if app.debug:
            file_handle = RotatingFileHandler(filename, maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8')
            file_handle.setFormatter(formatter)
            app.logger.setLevel(log_level)
            app.logger.addHandler(file_handle)

        app.logger.removeHandler(default_handler)

        if app.debug: app.logger.addHandler(console_handler)
